package com.siemens.industrial.app;

import org.springframework.jdbc.core.JdbcTemplate;

import javax.mail.MessagingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Yipin on 2016/11/29.
 */
public class EventImplementation {
    private JdbcTemplate jdbcTemplate;
    private static final String databaseTag = "{database}";
    private static final String getUserById = "select * from `siemens`.user where user_id = ?";
    private static final String getMails = "SELECT group_concat(a.email) mails FROM siemens.user_event_relation a  where a.event_id=?;";
    private static final String getMailConfig = "select * from `siemens`.system_config where system_key ='mail_config_key'";
    private static final String getTenantUser = "select * from `" + databaseTag + "`.user where user_id =?";
    private static final String getOneTenantByKey = "select * from siemens.tenant where tenant_key =?";
    private static final String insertMessage = "INSERT INTO `siemens`.`message` (`event_id`, `status`, `executant`, `operands`, `service_id`) VALUES (?, ?, ?, ?, ?);";

    public void sendMail(String info) {
        System.out.println("<<<<<<<<<<<<<<<<<<<<");
        jdbcTemplate = DBHelper.getJdbcTemplate();

        if (jdbcTemplate == null) {
            System.out.println("Get database connection failed.");
            return;
        }
        Map<String, Object> map = SendMail.buildJsonToMap(info);
        List<Map<String, Object>> mailConfig = this.getMailConfig();
        if (mailConfig == null || mailConfig.size() == 0)
            return;
        Map<String, String> pps = SendMail.buildMailProperties(mailConfig.get(0).get("system_value").toString());
        if (map.get("type").equals("userUnEnabled")) {
            List<Map<String, Object>> user = this.getUserById(map.get("userId").toString());
            Map<String, Object> mails = this.getMailsByEvent("5");
            String[] mail = (mails.get("mails").toString()).split(",");
            String message = "平台管理员“" + user.get(0).get("user_name").toString() + "”被禁用";
            buildMessage(mail, pps, "5", "平台管理员禁用通知", "admin", user.get(0).get("user_name").toString(), message);
        } else if (map.get("type").equals("tenantUserUnEnabled")) {
            List<Map<String, Object>> user = this.getUserById(map.get("currentUser").toString());
            Map<String, Object> tenant = this.getTenantById(map.get("tenantId").toString(), map.get("tenantUserId").toString());
            Map<String, Object> mails = this.getMailsByEvent("2");
            String[] mail = (mails.get("mails").toString()).split(",");
            String message = "管理员" + user.get(0).get("user_name") + "禁用了租户“" + tenant.get("user_name").toString() + "”";
            buildMessage(mail, pps, "2", "租户账户禁用通知", user.get(0).get("user_name").toString(), tenant.get("user_name").toString(), message);
        } else if (map.get("type").equals("createTenant")) {
            List<Map<String, Object>> user = this.getUserById(map.get("currentUser").toString());
            Map<String, Object> tenant = this.getTenantByKey(map.get("key").toString());
            Map<String, Object> mails = this.getMailsByEvent("1");
            String[] mail = (mails.get("mails").toString()).split(",");
            String message = "管理员" + user.get(0).get("user_name").toString() + "创建了租户“" + tenant.get("tenant_name").toString() + "”";
            buildMessage(mail, pps, "1", "创建租户通知", user.get(0).get("user_name").toString(), tenant.get("tenant_name").toString(), message);//mail,event_id,executant,operands,title,
        }
        System.out.println("send mail");
        System.out.println(">>>>>>>>>>>>>>>>>>>>" + new Date());
    }

    public List<Map<String, Object>> getUserById(String userId) {
        return jdbcTemplate.queryForList(getUserById, userId);
    }

    public List<Map<String, Object>> getMailConfig() {
        return jdbcTemplate.queryForList(getMailConfig);
    }

    public Map<String, Object> getMailsByEvent(String eventId) {
        return jdbcTemplate.queryForMap(getMails, eventId);
    }

    public Map<String, Object> getTenantById(String tenantId, String userId) {
        return jdbcTemplate.queryForMap(getTenantUser.replace(databaseTag, tenantId), userId);
    }

    public Map<String, Object> getTenantByKey(String key) {
        return jdbcTemplate.queryForMap(getOneTenantByKey, key);
    }

    public void buildMessage(String[] mail, Map<String, String> pps, String eventId, String title, String executant, String operands, String message) {
        if (mail.length > 0) {
            jdbcTemplate.update(insertMessage, eventId, 0, executant, operands, null);//// TODO: 2017/3/6  update
            try {
                SendMail send = new SendMail(pps);
                send.setMailParam(title, mail, message, pps.get("mailAddress_key"));
                send.send();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
}
